package cn.edu.gxu.xingjian.teacherassistant.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import cn.edu.gxu.xingjian.teacherassistant.domain.CourseCategory;
import cn.edu.gxu.xingjian.teacherassistant.domain.Curriculum;
import cn.edu.gxu.xingjian.teacherassistant.domain.TeachingMode;
import cn.edu.gxu.xingjian.teacherassistant.domain.Useres;
import cn.edu.gxu.xingjian.teacherassistant.domain.UseresCurr;
import cn.edu.gxu.xingjian.teacherassistant.util.Session;

@RequestMapping("/curriculums")
@Controller
@RooWebScaffold(path = "curriculums", formBackingObject = Curriculum.class)
public class CurriculumController {

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
	public String create(@Valid Curriculum curriculum,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest) {
		if (bindingResult.hasErrors()) {
			populateEditForm(uiModel, curriculum);
			return "curriculums/create";
		}
		uiModel.asMap().clear();
		curriculum.persist();
		return "redirect:/curriculums/"
				+ encodeUrlPathSegment(curriculum.getId().toString(),
						httpServletRequest);
	}

	@RequestMapping(params = "form", produces = "text/html")
	public String createForm(Model uiModel) {
		populateEditForm(uiModel, new Curriculum());
		return "curriculums/create";
	}

	@RequestMapping(value = "/{id}", produces = "text/html")
	public String show(@PathVariable("id") Long id, Model uiModel) {
		uiModel.addAttribute("curriculum", Curriculum.findCurriculum(id));
		uiModel.addAttribute("itemId", id);
		return "curriculums/show";
	}

	@RequestMapping(produces = "text/html")
	public String list(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel) {
		if (page != null || size != null) {
			int sizeNo = size == null ? 10 : size.intValue();
			final int firstResult = page == null ? 0 : (page.intValue() - 1)
					* sizeNo;
			uiModel.addAttribute("curriculums",
					Curriculum.findCurriculumEntries(firstResult, sizeNo));
			float nrOfPages = (float) Curriculum.countCurriculums() / sizeNo;
			uiModel.addAttribute(
					"maxPages",
					(int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
							: nrOfPages));
		} else {
			uiModel.addAttribute("curriculums", Curriculum.findAllCurriculums());
		}
		List<Curriculum> ls = new ArrayList<Curriculum>(3);
		List<UseresCurr> ucls = new ArrayList<UseresCurr>(3);

		if (page != null || size != null) {
			int sizeNo = size == null ? 10 : size.intValue();
			final int firstResult = page == null ? 0 : (page.intValue() - 1)
					* sizeNo;
			ucls = UseresCurr
					.findUseresCurrsByUid(
							Useres.findUseres(Session.getInstance().getUid()))
					.setFirstResult(firstResult).setMaxResults(sizeNo)
					.getResultList();
			for (UseresCurr uc : ucls) {
				ls.add(uc.getCid());
			}
			uiModel.addAttribute("selectedCurriculums", ls);
			float nrOfPages = (float) Curriculum.countCurriculums() / sizeNo;
			uiModel.addAttribute(
					"selectedMaxPages",
					(int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
							: nrOfPages));
		} else {
			ucls = UseresCurr.findUseresCurrsByUid(
					Useres.findUseres(Session.getInstance().getUid()))
					.getResultList();
			for (UseresCurr uc : ucls) {
				ls.add(uc.getCid());
			}
			uiModel.addAttribute("selectedCurriculums", ls);
		}
		return "curriculums/list";
	}

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
	public String update(@Valid Curriculum curriculum,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest) {
		if (bindingResult.hasErrors()) {
			populateEditForm(uiModel, curriculum);
			return "curriculums/update";
		}
		uiModel.asMap().clear();
		curriculum.merge();
		return "redirect:/curriculums/"
				+ encodeUrlPathSegment(curriculum.getId().toString(),
						httpServletRequest);
	}

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
	public String updateForm(@PathVariable("id") Long id, Model uiModel) {
		populateEditForm(uiModel, Curriculum.findCurriculum(id));
		return "curriculums/update";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
	public String delete(@PathVariable("id") Long id,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel) {
		Curriculum curriculum = Curriculum.findCurriculum(id);
		curriculum.remove();
		uiModel.asMap().clear();
		uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
		uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
		return "redirect:/curriculums";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "text/html")
	public String select(@PathVariable("id") Long id,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel, HttpServletRequest httpServletRequest) {
		Useres u = Useres.findUseres(Session.getInstance().getUid());
		Curriculum c = Curriculum.findCurriculum(id);
		
		if (UseresCurr.findUseresCurrsByUidAndCid(u, c).getResultList().size()==0) {
			UseresCurr uc = new UseresCurr();
			uc.setUid(u);
			uc.setCid(c);
			uc.persist();
			uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
			uiModel.addAttribute("size",
					(size == null) ? "10" : size.toString());
		}
		return list(page, size, uiModel);
	}

	void populateEditForm(Model uiModel, Curriculum curriculum) {
		uiModel.addAttribute("curriculum", curriculum);
		uiModel.addAttribute("coursecategorys",
				CourseCategory.findAllCourseCategorys());
		uiModel.addAttribute("teachingmodes",
				TeachingMode.findAllTeachingModes());
	}

	String encodeUrlPathSegment(String pathSegment,
			HttpServletRequest httpServletRequest) {
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {
		}
		return pathSegment;
	}
}
